package adapter.handler;


import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.jpos.iso.ISOMsg;
import org.jpos.iso.ISOUtil;
import org.jpos.iso.packager.GenericPackager;


public class LCPHandler extends IoHandlerAdapter{
	private Logger handlerLogger=Logger.getLogger(this.getClass()); 
	private Integer protocolLength;

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		
		//handlerLogger.info("rcvd: "+ISOUtil.hexString((byte[]) message));
		byte[] mess=removeProtocolLength((byte[]) message,protocolLength);
		System.out.println(ISOUtil.hexString(mess));
        GenericPackager gvPackager=new GenericPackager("cfg/BASE-IJPOS.xml");
        gvPackager.setHeaderLength(22);
        ISOMsg msg=new ISOMsg();
        msg.setPackager(gvPackager);
        msg.unpack(mess);
        msg.dump(System.out, "Request: ");
        
        
        msg.set(39,"00");
        msg.recalcBitMap();
        
        msg.dump(System.out, "Response: ");
        session.write(addLen(msg.pack()));
	}
	
    public static byte[] addLen(byte[] msg){
        int len=msg.length;
        byte[] byteLen;
        if(len > 4095){
            byteLen=ISOUtil.hex2byte( Integer.toHexString( len )+"0000" );
        } else if(len>255){
            byteLen=ISOUtil.hex2byte( "0"+Integer.toHexString( len )+"0000" );
        }else{
            byteLen=ISOUtil.hex2byte( "00"+Integer.toHexString( len )+"0000" );
        }
        
        msg[4]=byteLen[1];
        msg[3]=byteLen[0];
        
        return ISOUtil.concat( byteLen, msg );
    }
    
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		cause.printStackTrace();
	}
	
	@Override
	public void sessionCreated(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		handlerLogger.info("Connected to "+ session.getRemoteAddress().toString());
		//session.write(new byte[]{(byte)0x00,(byte)0x3E});
	}
	
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		//super.sessionClosed(session);
		//System.out.println("disconnected");
	}
	
	public byte[] removeProtocolLength(byte[] msg, int noOfBytes) {
		//byte[] msgBody=Arrays.copyOfRange(msg,noOfBytes, msg.length);
		byte [] msgBody=new byte[msg.length-noOfBytes];
		//System.arraycopy(msg,0,msgBody,noOfBytes,msg.length-noOfBytes);
		System.arraycopy(msg,noOfBytes,msgBody,0,msg.length-noOfBytes);
		return msgBody;
	}

	public Integer getProtocolLength() {
		return protocolLength;
	}

	public void setProtocolLength(Integer protocolLength) {
		this.protocolLength = protocolLength;
	}
	
	
	
}
